//
//  SelectXSViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/6/7.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "SelectXSViewController.h"
#import "ProjectData.h"
#import "ProjectManager.h"
#import "UITapView.h"

@interface SelectXSViewController ()

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;

@end

@implementation SelectXSViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    //[self loadData];
}

/**
 *  初始化数据
 */
- (void)initData {
    self.dataSource = [NSMutableArray new];
}

#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"系列选择";
    
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
}

#pragma mark - 加载数据
/**
 *  加载视图所有的数据
 */
- (void)loadData {
    //[self loadNationData];
    [self loadProductSeries:self.tag];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self loadData];
}


/**
 *  获得项目中可选的产品系列列表
 *
 *  @param tag
 */
- (void)loadProductSeries:(NSString *)tag {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:tag forKey:@"tag"];
    [param setValue:[[ProjectManager manager] projectId] forKey:@"pid"]; //project ID
    
    [HttpClient getWithUrl:HTTP_GET_PROJECT_PRODUCT_SERIES token:[[AccountManager manager]token] paramDic:param resultClass:[GuidData class] success:^(GuidData *obj) {
        [self.dataSource removeAllObjects];
        if (obj.getCandidateXlsResult != nil && obj.getCandidateXlsResult.count > 0) {
            int section = 0;
            for (GuidData *item in obj.getCandidateXlsResult) {
                //item.isClosed = YES;
                [self.dataSource addObject:item];
                [self loadProductSeriesXs:item andTag:tag andSection:(int)section];
                section ++;
            }
        }
        else {
            kTipAlert(@"没有可选的系列！");
        }
        [self.tableView reloadData];
        CMLog(@"%@", obj);
    } failure:^(NSError *error) {
        CMLog(@"%@", error);
    }];
}

/**
 *  获取项目中选择了的型式列表
 *
 *  @param series 系列
 *  @param data   系列数据
 */
- (void)loadProductSeriesXs:(GuidData *)data andTag:(NSString *)tag andSection:(int)section{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:tag forKey:@"tag"];
    [param setValue:data.guidId forKey:@"xl"]; //系列
    [param setValue:[NSNumber numberWithInt:1] forKey:@"ac"]; //0 仅包括未上市  1 仅包括已上市 2 已上市未上市都包括
    
    [HttpClient getWithUrl:HTTP_GET_PROJECT_PRODUCT_XS_BY_XL token:[[AccountManager manager]token] paramDic:param resultClass:[GuidData class] success:^(GuidData *obj) {
        
        if (obj.getProductXssResult != nil && obj.getProductXssResult.count > 0) {
            data.xsData = [NSMutableArray new];
            [data.xsData addObjectsFromArray:obj.getProductXssResult];
        }
        else {
            data.xsData = nil;
        }
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
        CMLog(@"%@", obj);
    } failure:^(NSError *error) {
        CMLog(@"%@", error);
    }];
}


#pragma mark - 事件响应

#pragma mark - UIAlertViewDelegate 代理

#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    GuidData *data = [self.dataSource objectAtIndex:section];
    if (data.xsData != nil && !data.isClosed) {
        return data.xsData.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"XSCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.textLabel.textColor = CM_TABLE_TITLE_COLOR;
    cell.detailTextLabel.textColor = CM_TABLE_INFO_COLOR;
    GuidData *data = [self.dataSource objectAtIndex:indexPath.section];
    GuidData *item = [data.xsData objectAtIndex:indexPath.row];
    cell.textLabel.text = item.name;
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    GuidData *data = [self.dataSource objectAtIndex:indexPath.section];
    GuidData *item = [data.xsData objectAtIndex:indexPath.row];
    if (self.userSelectedBlock != nil) {
        self.userSelectedBlock(item);
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return DEFAULT_SECTION_HEIGHT;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.dataSource.count == 0) {
        return nil;
    }
    GuidData *data = [self.dataSource objectAtIndex:section];
    
    UITapView *headView = [[UITapView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, DEFAULT_SECTION_HEIGHT)];
    [headView setBgColor:[UIColor whiteColor] andHighLightBgColor:[UIColor whiteColor]];
    [headView addTargetsBlock:^(id obj) {
        data.isClosed = !data.isClosed;
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
    
    UILabel *label;
    label = [UILabel labelSingleLineFontSize:kListDetailFontSize content:data.name];
    label.textColor = CM_BLUE_COLOR;
    label.x = CELL_PADDING_LEFT;
    label.centerY = headView.height/2;
    [headView addSubview:label];
    
    UIImage *image;
    if (!data.isClosed) {
        image = [UIImage imageNamed:@"select_user_up"];
    }
    else {
        image = [UIImage imageNamed:@"select_user_down"];
    }
    
    UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
    imageView.x = kScreen_Width - CELL_PADDING_RIGHT - imageView.size.width;
    imageView.centerY = headView.height/2;
    [headView addSubview:imageView];
    
    return headView;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
